package cn.puppy.postgres.demo.service;

import cn.hutool.core.io.FileUtil;
import cn.puppy.postgres.demo.dao.db2.ResultDatasourceDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author zhanglm
 * @createDate 2024/08/06 10:51
 * @package cn.puppy.postgres.demo.service
 * @message service定时任务
 */
@Slf4j
@Service
@EnableScheduling
public class TaskService {

//    @Resource
//    private AccessDatasource1Dao accessDatasource1Dao;

    @Resource
    private ResultDatasourceDao resultDatasourceDao;

    /**
     * 项目启动立即执行
     * cron表达式：每2分钟执行一次
     */
//    @PostConstruct
    @Scheduled(cron = "0 */1 * * * ?")
//    @Scheduled(cron = "*/30 * * * * ?")
    @Transactional(rollbackFor = RuntimeException.class)
    public void execute() {
        log.info("***********************task-begin**************************");
        log.info("**************************************************************");
        log.info("         shandong MaoLong Steel Co., Ltd.IT DEPT");
        log.info("            Labtory Dept data(18 type element) synchroize");
        log.info("                Auther:nicepuppy(zlm)");
        log.info("                    DATE:2024/08/05");
        log.info("**************************************************************");

        //30秒一次，读取完成后删除，加判断读取不到文件直接退出
        String path = "D:\\实验室\\Filename" ;

        final boolean exist = FileUtil.exist(path);
        if(exist){
            String str = FileUtil.readUtf8String(new File(path));
            String[] rows = str.split("\r\n");

            String[][] datas = new String[50][50];
            Map<String,Object> maps = new HashMap<>();
            for(int i = 1 ; i < rows.length;i++){//行循环
                String[] s = rows[i].trim().split(" ");//按空格分列
                if(i == 1){
                    maps.put("transferCode",s[1]);
                }else{
                    if(s[s.length-1] != null){
                        Object o = Double.parseDouble(s[s.length-1].toString());
                        maps.put(s[1],String.format("%.3f",o));
                    }

                }

            }

            HashMap<String, Object> params = new HashMap<>();
            String transferCode = maps.get("transferCode") == null?"":maps.get("transferCode").toString();
            if(transferCode != null && !transferCode.equals("")){List<String> itemIdList = new ArrayList<>();
                Set<String> keys = maps.keySet(); // 获取所有的key集合
                for (String key : keys) {
                    if(!key.equals("transferCode")){
                        params.put("testValue", maps.get(key).toString());
                        Integer count = resultDatasourceDao.countSampleno(transferCode);
                        if(count > 0){
                            String itemId = resultDatasourceDao.getManufactItemByNameAndTransferCode(key.equals("T.Fe")?"TFe":key, transferCode);

                            if(itemId != null){
                                long itemIdLong = Long.parseLong(itemId);
                                params.put("id",itemIdLong);
                                int i1 = resultDatasourceDao.updateManufactItemById(params);
                                itemIdList.add(itemId);
                                if(i1 > 0){
                                    int i2 = resultDatasourceDao.updateManufactItemOperationTimeById(itemIdLong);
                                }
                            }

                        }
                    }

                }
                log.warn("本次定时任务更新数据的条数：" + itemIdList.size() + "，id集合为：" + itemIdList);
                log.info("***********************task-end**************************");
                //清空集合
                itemIdList.clear();
                FileUtil.del(path);
            }else {
                log.warn("NO transfercode,just delete the file");
                FileUtil.del(path);
            }

        }else{
            System.out.println("file not exists!");
        }
    }
}
